var chatRecordMap = new Map();
// 聊天列表
var hotRecordMap;

var currentChatId;
var currentChatName;
var currentChatType;
var friendMap;
var friendSelected = [];
var webSocket;

$(function(){
    initWindowElement();
    initFastMsgEvent();
    initSocketClient();
    //回车发送
    $(document).keydown(function(event){
        if(event.keyCode == 13){
            var e = e || event;
            send(2, 'font', null, userPic);
            stopDefaultKey(e)
        }
    });

});

function initWindowElement(){
    $("#talkbody").hide();
    $("#albumBody").hide();
    $("#talkbox").hide();
    $("#friend_nickName").text("");
    //初始化滚动条
    setScroll();
}

function setScroll(){
    $("#chatbox").slimScroll({
        height: "473px",
        wheelStep: 10,
        alwaysVisible: true,
    });
}

function findUserByUserName() {
    var userCode = $(".user_code_text").val();
    $.ajax({
        url: "/users/findByUserCode",
        data: {
            userCode: userCode,
            userId: userId
        },
        type: "POST",
        beforeSend: function (XHR) {
            $.AMUI.progress.start();
        },
        complete: function () {
            $.AMUI.progress.done();
        },
        success: function (result) {
            if (result.respCode == "1000") {
                $(".chat_content ul").remove();
                $(".chat_content").append('<ul class="user_list">\n' +
                    '                    <li class="chat_user_list">\n' +
                    '                        <p>添加好友</p>\n' +
                    '                    </li>\n' +
                    '                </ul>');

                $(".chat_user_list").append('<div class="friends_box"><div class="user_head"><img src="'+result.userInfo.picSmall+'"/></div><div class="user_text"><p class="user_name">'+result.userInfo.userName+'</p><p class="user_message"></p></div><div class="user_time"><button class="am-btn-primary am-btn-sm" id="'+result.userInfo.userId+'_'+result.userInfo.userName+'_'+result.userInfo.picSmall+'" onclick="friendRequest(id)">邀请</button></div></div>');
            }
        },
        error: function (xmlHttpReq, error, ex) {
            swal("发生了一些问题", xmlHttpReq.responseJSON.error, "error");
        }
    });
}

function friendRequest(friendUserInfo) {
    var friendInfo = friendUserInfo.split('_');
    var messagePayLoad = {
        "type": 3,
        "fileType": 0,
        "receive":friendInfo[1],
        "receiveUserId":friendInfo[0],
        "send":userName,
        "sendUserId":userId,
        "info":"你好，我是" + userName + ",请求添加你为好友！"

    };
    webSocket.send(JSON.stringify(messagePayLoad));
    $(".chat_user_list div").remove();
    $(".chat_user_list").append('<div class="friends_box">\n' +
        '                            <div class="user_head"><img src="'+friendInfo[2]+'"/></div>\n' +
        '                            <div class="user_text">\n' +
        '                                <p class="user_name">'+friendInfo[1]+'</p>\n' +
        '                                <p class="user_message">已邀请</p>\n' +
        '                            </div>\n' +
        '                        </div>');

}

function initFastMsgEvent() {
    var si1 = document.getElementById('si_1');
    var si2 = document.getElementById('si_2');
    var si3 = document.getElementById('si_3');
    si1.onclick = function () {
        si1.style.background = "url(images/icon/head_2_1.png) no-repeat";
        si2.style.background = "";
        si3.style.background = "";
        $(".chat_content ul").remove();
        $(".chat_content").append('<ul class="user_list">\n' +
            '                    <li class="chat_user_list">\n' +
            '                        <p>聊天列表</p>\n' +
            '                    </li>\n' +
            '                </ul>');

        for(var key in hotRecordMap){
            var splitId = hotRecordMap[key].id.split('_');
            // 好友申请显示的内容不一样
            if (splitId[1]==3) {
                $(".chat_user_list").append('   <div class="friends_box">\n' +
                    '                            <div class="user_head"><img src="'+hotRecordMap[key].pic+'" /></div>\n' +
                    '                            <div class="user_text">\n' +
                    '                                <p class="user_name">'+hotRecordMap[key].name+'</p>\n' +
                    '                                <p class="user_message" title="'+hotRecordMap[key].info+'">'+hotRecordMap[key].info+'</p>\n' +
                    '                            </div>\n' +
                    '                            <div class="user_time"><button class="am-btn-warning am-btn-sm" id="'+splitId[0]+'_'+hotRecordMap[key].receiveUserId+'_'+hotRecordMap[key].receive+'" onclick="addFriend(id)">同意</button></div>\n' +
                    '                        </div>');
            } else {
                $(".chat_user_list").append('<div class="friends_box" id ="'+hotRecordMap[key].id+'" onclick="clickUserCard(id)"><div class="user_head"><img src="'+hotRecordMap[key].pic+'"/></div><div class="friends_text"><p class="user_name">'+hotRecordMap[key].name+'</p></div></div>');
            }

        };

    };
    si2.onclick = function () {
        si1.style.background = "";
        si2.style.background = "url(images/icon/head_3_1.png) no-repeat";
        si3.style.background = "";
        $(".chat_content ul").remove();
        $(".chat_content").append('<ul class="user_list">\n' +
            '                    <li class="chat_user_list">\n' +
            '                        <p>好友列表</p>\n' +
            '                    </li>\n' +
            '                </ul>');
        // 获取好友列表
        getFriendList();
    };
    si3.onclick = function () {
        si1.style.background = "";
        si2.style.background = "";
        si3.style.background = "url(images/icon/head_4_1.png) no-repeat";
        $(".chat_content ul").remove();
        $(".chat_content").append('<ul class="icon_list">\n' +
            '                    <li>\n' +
            '                        <div class="icon"><img src="images/icon/icon.png" alt=""/></div>\n' +
            '                        <span>朋友圈</span>\n' +
            '                    </li>\n' +
            '                    <li onclick="clickAlbum()">\n' +
            '                        <div class="icon"><img src="images/icon/icon2.png" alt=""/></div>\n' +
            '                        <span>相册</span>\n' +
            '                    </li>\n' +
            '                </ul>');
    };

    si1.style.background = "url(images/icon/head_2_1.png) no-repeat";
}

function dragover(ev) {
    ev.preventDefault();
    $("#input_box div").remove();
    $("#input_box").append('<div class="drag_inner_div">将文件拖拽到这里</div>');
}

function dragleave(ev) {
    $("#input_box div").remove();
}
function drop(ev) {
    ev.preventDefault();
    $("#input_box div").remove();
}

function initSocketClient() {
    //userId = getCookie("USER_ID");
    if (!userId) {
        swal("抱歉!", "未正常登录", "error");
        addCookie("USER_ID",userId,"1h");
        return;
    }
    if ('WebSocket' in window) {
        console.log("获取websocket");
        webSocket = new WebSocket("ws://"+serverIp+"/channel");
    }
    webSocket.onopen = function () {
        console.log("websocket is open....");
        // 发送上线消息
        send(1, 'font', null, userPic);
    };
    webSocket.onerror = function (e) {
        console.log("websocket is error");
    };
    webSocket.onmessage = function (message) {
        console.log("接收消息 : " + message.data);
        var messageJson = JSON.parse(message.data);
        var type = messageJson.type;
        var isGroup = messageJson.isGroup;
        //上下线通知类型
        if (type == 1) {
            //上线
            $(".chat_user_list").append('<div class="friends_box" id ="'+messageJson.sendUserId+'_2" onclick="clickUserCard(id)"><div class="user_head"><img src="images/head/file.jpg"/></div><div class="friends_text"><p class="user_name">'+messageJson.send+'</p></div></div>');
            hotRecordMap = new Map();
            var recordMap = {
                id: messageJson.sendUserId+'_2',
                pic: 'images/head/file.jpg',
                name: messageJson.send
            };
            hotRecordMap[recordMap.id]=recordMap;

        }
        //普通到达消息
        if (type == 2) {
            if (currentChatId == messageJson.sendUserId) {
                var talkElement = null;
                if (messageJson.fileType == 'font') {
                    talkElement = '<li class="other"><img src="'+messageJson.pic+'" title="'+messageJson.receive+'"><span><code">'+messageJson.info+'</code></span></li>';
                } else if (messageJson.fileType == 'pic'){
                    talkElement = '<li class="other"><img src="'+messageJson.pic+'" title="'+messageJson.receive+'"><span><img class="show_chat_img" src='+messageJson.info+'></span></li>';
                }

                $("#chatbox").append(talkElement);
            }
            var chatRecordOnceBean = {
                "type":"other",
                "fileType": messageJson.fileType,
                "msg":messageJson.info,
                "nickName":messageJson.send,
                "pic": messageJson.pic
            };
            storageChatReocrd(messageJson.sendUserId, chatRecordOnceBean);
            notify(messageJson.send+"发来一条消息",messageJson.info);
        }
        // 好友申请
        if (type == 3) {
            $(".chat_content ul").remove();
            $(".chat_content").append('<ul class="user_list">\n' +
                '                    <li class="chat_user_list">\n' +
                '                        <p>新朋友</p>\n' +
                '                    </li>\n' +
                '                </ul>');

            $(".chat_user_list").append('   <div class="friends_box">\n' +
                '                            <div class="user_head"><img src="'+messageJson.pic+'" /></div>\n' +
                '                            <div class="user_text">\n' +
                '                                <p class="user_name">'+messageJson.send+'</p>\n' +
                '                                <p class="user_message" title="'+messageJson.info+'">'+messageJson.info+'</p>\n' +
                '                            </div>\n' +
                '                            <div class="user_time"><button class="am-btn-warning am-btn-sm" id="'+messageJson.sendUserId+'_'+messageJson.receiveUserId+'_'+messageJson.receive+'" onclick="addFriend(id)">同意</button></div>\n' +
                '                        </div>');
            var recordMap = {
                id: messageJson.sendUserId+'_3',
                pic: messageJson.pic,
                name: messageJson.send,
                info: messageJson.info,
                receiveUserId: messageJson.receiveUserId,
                receive: messageJson.receive
            };
            hotRecordMap[recordMap.id]=recordMap;
        }
        if (type == 4) {
            //群聊上线
            $(".chat_user_list").append('<div class="friends_box" id ="'+messageJson.receiveUserId+'_5" onclick="clickUserCard(id)"><div class="user_head"><img src="'+messageJson.pic+'"/></div><div class="friends_text"><p class="user_name">'+messageJson.receive+'</p></div></div>');
            // currentChatId = messageJson.receiveUserId;
            console.log('4;' + messageJson.receiveUserId);
            var recordMap = {
                id: messageJson.receiveUserId+'_5',
                pic: messageJson.pic,
                name: messageJson.receive
            };
            hotRecordMap[recordMap.id]=recordMap;

        }
        if (type == 5) {
            // 群聊信息处理
            console.log('5;' + messageJson.receiveUserId);
            if (currentChatId == messageJson.receiveUserId) {
                var talkElement = null;
                if (messageJson.fileType == 'font') {
                    talkElement = '<li class="other"><img src="'+messageJson.pic+'" title="'+messageJson.send+'"><span><code">'+messageJson.info+'</code></span></li>';
                } else if (messageJson.fileType == 'pic'){
                    talkElement = '<li class="other"><img src="'+messageJson.pic+'" title="'+messageJson.send+'"><span><img class="show_chat_img" src='+messageJson.info+'></span></li>';
                }

                $("#chatbox").append(talkElement);
            }
            var chatRecordOnceBean = {
                "type":"other",
                "fileType": messageJson.fileType,
                "msg":messageJson.info,
                "nickName":messageJson.send,
                "pic": messageJson.pic
            };
            storageChatReocrd(messageJson.receiveUserId, chatRecordOnceBean);
            notify(messageJson.send+"发来一条群聊消息",messageJson.info);
        }
        // 下线
        if (type == 0) {
            var talkElement = '<li class="other"><a class="am-badge am-badge-danger">!</a><img src="images/head/15.jpg" title="'+messageJson.receive+'"><span><code>'+messageJson.info+'</code></span></li>';
            $("#chatbox").append(talkElement);
            var chatRecordOnceBean = {
                "type":"other",
                "fileType": 0,
                "msg":messageJson.info,
                "nickName":messageJson.send
            };
            storageChatReocrd(messageJson.sendUserId, chatRecordOnceBean);
        }
    };
}


function clickUserCard(id){

    var userInfoSplit = id.split('_');
    $("#albumBody").hide();
    $("#talkbody").show();
    $("#talkbox").show();

    $(".chat_user_list div").each(function () {
        $(this).removeClass("user_active");
    });
    $("#"+id + "").toggleClass("user_active");
    //获取当前消息窗口

    currentChatName =  $("#" + id + ">div>p").text();;
    $("#friend_nickName").text(currentChatName);
    currentChatType = userInfoSplit[1];
    currentChatId = userInfoSplit[0];
    // 如果热聊列表不包含点击的用户卡片，新增
    if (!hotRecordMap[id]) {
        var friend = friendMap[currentChatId];
        //更新聊天列表
        var recordMap = {
            id: id,
            pic: friend.friendPic,
            name: currentChatName
        };
        hotRecordMap[recordMap.id]=recordMap;
    }
    //加载聊天记录
    setChatRecord(userInfoSplit[0]);
}

function uploadPic() {
    var windowUrl = window.URL || window.webkitURL;
    var input = document.getElementById('uploadPic');
    input.click();
    input.onchange = function(){
        var object=this;
        // $("#input_box").append('<img id="preview"/>');
        // $("#preview").attr('src', windowUrl.createObjectURL(object.files[0]));
        var form = new FormData(); // FormData 对象
        form.append("file", object.files[0]); // 文件对象
        $.ajax({
            url: "/file/upload",
            data: form,
            dataType: "json",
            type: "POST",
            contentType: false,
            processData: false,
            beforeSend: function (XHR) {
                $.AMUI.progress.start();
            },
            complete: function () {
                $.AMUI.progress.done();
            },
            success: function (result) {
                if (result.respCode == "1000") {
                    send(2, result.fileType, result.previewPath, userPic);
                    // $("#input_box").append("<img src="+result.previewPath+"/>")
                }
            },
            error: function (xmlHttpReq, error, ex) {
                swal("发生了一些问题", xmlHttpReq.responseJSON.error, "error");
            }
        });


    }
}

function uploadFile() {
    var input = document.getElementById('uploadFile');
    input.click();
    input.onchange = function(){
        var object=this;
        var form = new FormData();
        form.append("file", object.files[0]);
        $.ajax({
            url: "/file/upload",
            data: form,
            dataType: "json",
            type: "POST",
            contentType: false,
            processData: false,
            beforeSend: function (XHR) {
                $.AMUI.progress.start();
            },
            complete: function () {
                $.AMUI.progress.done();
            },
            success: function (result) {
                if (result.respCode == "1000") {
                    send(2, result.fileType, result.previewPath, userPic);
                }
            },
            error: function (xmlHttpReq, error, ex) {
                swal("发生了一些问题", xmlHttpReq.responseJSON.error, "error");
            }
        });


    }
}


function setChatRecord(id){

    $("#chatbox").empty();
    var bean = chatRecordMap.get(id);
    if(bean != undefined){
        for(var i =0 ; i<bean.length; i++){
            var type = bean[i].type;
            var msg = bean[i].msg;
            var nickName = bean[i].nickName;
            var fileType = bean[i].fileType;
            var pic = bean[i].pic;
            var talkElement = null;
            if(type == 'me'){
                switch (fileType) {
                    case 'font':
                        talkElement = '<li class="me"><img src="'+pic+'" title="'+nickName+'"><span>' + msg + '</span></li>';
                        break;
                    case 'pic':
                        talkElement = '<li class="me"><img src="'+pic+'" title="'+nickName+'"><span><img class="show_chat_img" src='+msg+'/></span></li>';
                        break;
                }

            }
            if(type == 'other'){
                switch (fileType) {
                    case 'font':
                        talkElement = '<li class="other"><img src="'+pic+'" title="' + nickName + '"><span>' + msg + '</span></li>';
                        break;
                    case 'pic':
                        talkElement = '<li class="other"><img src="'+pic+'" title="' + nickName + '"><span><img class="show_chat_img" src='+msg+'/></span></li>';
                        break;
                }
            }
            $("#chatbox").append(talkElement);
        }
    }
}

// 统一好友邀请
function addFriend(id) {
    var userList = id.split('_');
    $.ajax({
        url: "/friend/addFriend",
        data: {
            userId: userList[0],
            friendUserId: userList[1]
        },
        type: "POST",
        beforeSend: function (XHR) {
            $.AMUI.progress.start();
        },
        complete: function () {
            $.AMUI.progress.done();
        },
        success: function (result) {
            if (result.respCode == "1000") {
                // $(".chat_user_list div").remove();
                // $(".chat_user_list").append(' <div class="friends_box">\n' +
                //     '                            <div class="user_head"><img src="images/head/1.jpg"/></div>\n' +
                //     '                            <div class="user_text">\n' +
                //     '                                <p class="user_name">'+userList[2]+'</p>\n' +
                //     '                                <p class="user_message">已同意</p>\n' +
                //     '                            </div>\n' +
                //     '                        </div>');
                var friend = hotRecordMap[userList[0]+'_3'];

                var recordMap = {
                    id: userList[1]+'_2',
                    pic: friend.pic,
                    name: friend.name
                };
                hotRecordMap[recordMap.id]=recordMap;
                delete hotRecordMap[userList[0]+'_3'];
                $(".chat_content ul").remove();
                $(".chat_content").append('<ul class="user_list">\n' +
                    '                    <li class="chat_user_list">\n' +
                    '                        <p>聊天列表</p>\n' +
                    '                    </li>\n' +
                    '                </ul>');
                for(var key in hotRecordMap){
                    var splitId = hotRecordMap[key].id.split('_');
                    // 好友申请显示的内容不一样
                    $(".chat_user_list").append('<div class="friends_box" id ="'+hotRecordMap[key].id+'" onclick="clickUserCard(id)"><div class="user_head"><img src="'+hotRecordMap[key].pic+'"/></div><div class="friends_text"><p class="user_name">'+hotRecordMap[key].name+'</p></div></div>');

                };
            }
        },
        error: function (xmlHttpReq, error, ex) {
            swal("发生了一些问题", xmlHttpReq.responseJSON.error, "error");
        }
    });
}

function newMessageBox() {
    var messageBoxHtml = '<div class=\"windows_body\"><div class=\"office_text\" style=\"height: 100%;\">' +
        '<ul class=\"content\" id=\"chatbox\"></ul></div></div>';
    $(".talk_window").append(messageBoxHtml);
}


function send(type, fileType, sendContent, pic){
    // console.log($("#input_box img").length);
    // if ($("#input_box img").length != 0) {
    //     var img = $("#input_box img").attr('src');
    //     console.log(img);
    //     var reader=new FileReader();
    //
    //     reader.readAsBinaryString(img);
    //     uploadPicToServer(reader);
    // }
    var content = null;
    if (sendContent) {
        content = sendContent;
    } else {
        content = $("#input_box").val();
    }
    if (currentChatType == 5) {
        type = currentChatType;
    }
    var messagePayLoad = {
        "type": type,
        "fileType": fileType,
        "pic": pic,
        "send":userName,
        "sendUserId":userId,
        "receiveUserId": currentChatId,
        "receive": currentChatName,
        "info":content

    };
    console.log('发送:' + JSON.stringify(messagePayLoad));
    webSocket.send(JSON.stringify(messagePayLoad));
    var chatRecordOnceBean = {
        "type":"me",
        "fileType": fileType,
        "msg":content,
        "nickName":userName,
        "pic": pic
    };
    storageChatReocrd(currentChatId, chatRecordOnceBean);
    var talkElement = null;
    if (fileType == 'font') {
        talkElement = '<li class="me"><img src="'+userPic+'" title="'+userId+'"><span>'+content+'</span></li>';
    } else if (fileType == 'pic') {
        talkElement = '<li class="me"><img src="'+userPic+'" title="'+userId+'"><span><img class="show_chat_img" src='+content+'></span></li>';
    }
    $("#chatbox").append(talkElement);
    //设置滚动条到最底部
    $("#chatbox").slimScroll({ scrollTo:  '9999999999px' });
    //设置task 元素颜色
    var talk = document.getElementById('talkbox');
    var text = document.getElementById('input_box');
    talk.style.background="#fff";
    text.style.background="#fff";
    //清空输入框
    $("#input_box").val("");

}

function storageChatReocrd(friendUserId, chatRecordOnceBean) {
    var chatRecord = chatRecordMap.get(friendUserId);
    if(!chatRecord){
        chatRecord = [];
    }
    chatRecord.push(chatRecordOnceBean);
    chatRecordMap.set(friendUserId,chatRecord);
}

function stopDefaultKey(e){
    if(e && e.preventDefault){
        e.preventDefault();
    }else{
        window.event.returnValue = false;
    }
    return false;
}


function getFriendList() {
    $.ajax({
        url: "/friend/getFriendList",
        data: {
            userId: userId
        },
        type: "POST",
        beforeSend: function (XHR) {
            $.AMUI.progress.start();
        },
        complete: function () {
            $.AMUI.progress.done();
        },
        success: function (result) {
            if (result.respCode == "1000") {
                $(".friends_box").remove();
                var friendList = result.friendList;
                friendMap = {};
                for(var index in friendList){
                    friendMap[friendList[index].friendUserId] = friendList[index];
                    $(".chat_user_list").append('<div class="friends_box" id ="'+friendList[index].friendUserId+'_2" onclick="clickUserCard(id)"><div class="user_head"><img src="'+friendList[index].friendPic+'"/></div><div class="friends_text"><p class="user_name">'+friendList[index].friendName+'</p></div></div>')
                }
            }
        },
        error: function (xmlHttpReq, error, ex) {
            swal("发生了一些问题", xmlHttpReq.responseJSON.error, "error");
        }
    });
}

function openGroupChat() {
    $.ajax({
        url: "/friend/getFriendList",
        data: {
            userId: userId
        },
        type: "POST",
        beforeSend: function (XHR) {
            $.AMUI.progress.start();
        },
        complete: function () {
            $.AMUI.progress.done();
        },
        success: function (result) {
            if (result.respCode == "1000") {
                $(".css_friend_list li").remove();
                $(".css_friend_selected_list li").remove();
                var friendList = result.friendList;
                friendMap = {};
                for(var index in friendList){
                    friendMap[friendList[index].friendUserId] = friendList[index];
                    $(".css_friend_list").append('<li> <div class="friend_list_box"> <div class="css_user_head"><img src="'+friendList[index].friendPic+'"/></div> <div class="css_friends_text">'+friendList[index].friendName+'</div> <div class="css_friends_checkbox"><input name="Friend" id="checkbox_'+friendList[index].friendUserId+'" type="checkbox" onclick="selectFriend(id)" value=""/> </div> </div> </li>');
                }
            }
        },
        error: function (xmlHttpReq, error, ex) {
            swal("发生了一些问题", xmlHttpReq.responseJSON.error, "error");
        }
    });
}

function selectFriend(message) {
    var userInfo = message.split('_');
    var selectUserId = userInfo[1];
    if (friendSelected.indexOf(selectUserId) != -1) {
        return;
    }
    $("#checkbox_"+selectUserId+"").attr("disabled","disabled");
    friendSelected.push(selectUserId);
    var selectUserName = friendMap[selectUserId].friendName;
    var selectUserPic = friendMap[selectUserId].friendPic;
    $(".css_friend_selected_list").append('<li id="delete_'+selectUserId+'">' +
        '                                    <div><img src="' + selectUserPic + '"/>' +
        '                                        <p>' + selectUserName + '</p>' +
        '                                    </div>' +
        '                                    <span id="span_'+selectUserId+'" class="am-badge am-badge-danger delete_selected" onclick="deleteSelect(id)">-</span></li>');

}

function deleteSelect(message) {
    var userInfo = message.split('_');
    var selectUserId = userInfo[1];
    $("#delete_"+selectUserId+"").remove();
    $("#checkbox_"+selectUserId+"").attr("checked", false);
    friendSelected.splice(selectUserId,1);
    $("#checkbox_"+selectUserId+"").removeAttr("disabled");
}

function confirmGroup() {
    if(friendSelected.length == 0) {
        swal("通知", "请选择需要群聊的好友", "info");
    } else {
        $('#doc-modal-group').modal('close');
        friendSelected = [];
    }
}

function closeModal() {
    friendSelected = [];
}

function confirmGroup() {
    friendSelected.push(userId);
    $.ajax({
        url: "/group/create",
        data: {
            groupName: $("#group_name").val(),
            chatList: JSON.stringify(friendSelected)
        },
        type: "POST",
        beforeSend: function (XHR) {
            $.AMUI.progress.start();
        },
        complete: function () {
            $.AMUI.progress.done();
        },
        success: function (result) {
            if (result.respCode == "1000") {
                currentChatId = result.roomId;
                currentChatName = result.roomName;
                // 发送socket消息，群号上线
                send(4, 'font', null, userPic);
            }
            $("#doc-modal-group").modal("close");
        },
        error: function (xmlHttpReq, error, ex) {
            swal("发生了一些问题", xmlHttpReq.responseJSON.error, "error");
        }
    });
    friendSelected = [];
    $("#group_name").val("");
}

function updateUserPic() {
    var windowUrl = window.URL || window.webkitURL;
    var input = document.getElementById('doc-form-file');
    input.click();
    input.onchange = function(){
        var object=this;
        // $("#input_box").append('<img id="preview"/>');
        // $("#preview").attr('src', windowUrl.createObjectURL(object.files[0]));
        var form = new FormData(); // FormData 对象
        form.append("file", object.files[0]); // 文件对象
        form.append("userId", userId);
        $.ajax({
            url: "/users/updateHead",
            data: form,
            dataType: "json",
            type: "POST",
            contentType: false,
            processData: false,
            beforeSend: function (XHR) {
                $.AMUI.progress.start();
            },
            complete: function () {
                $.AMUI.progress.done();
            },
            success: function (result) {
                if (result.respCode == "1000") {
                    swal("恭喜!", result.respMsg, "success");
                    userPic = result.previewPath;
                    $(".own_head").css("background", 'url(' + userPic + ')');
                    $("#head_upload").css("background", 'url(' + userPic + ')');
                }
            },
            error: function (xmlHttpReq, error, ex) {
                swal("发生了一些问题", xmlHttpReq.responseJSON.error, "error");
            }
        });


    }
}

$.emoticons({
    'activeCls':'trigger-active'
},function(api){
    var $content = $('textarea[name="content"]');
    var $result = $('#result');
    $('#format').click(function(){
        $result.html(api.format($content.val()));
    });
});